package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import java.io.IOException;

/*
* 自定义过滤器,拦截所有请求,验证是否已登录*/
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //Spring提供的用于比较路径的工具类
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //强转
        HttpServletRequest req =(HttpServletRequest)request;
        HttpServletResponse rep=(HttpServletResponse)response;
        //日志输出请求的路径
        log.info("拦截到请求,待验证:{}",req.getRequestURI());
        //自定义不需要处理的请求
        String  [] url=new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",    //移动端发送断行
                "/user/login"       //移动端登录
        };
        //判断请求路径是否属于可放行的类型
        String uri = req.getRequestURI();
        for (String s : url) {
            boolean match = PATH_MATCHER.match(s, uri);
            if(match){
                //匹配上,放行
                log.info("直接放行的请求:{}",uri);
                chain.doFilter(req, rep);
                return;
            }
        }

        //网页端
        //没有匹配上,拦截,判断是否已登录
        Long empId =(Long) req.getSession().getAttribute("employee");
        if(empId!= null){
            //已登录,在线程域中存储当前用户唯一id标识
            BaseContext.setThreadId(empId);
            log.info("已验证,已登录放行:{}",uri);
            //已登录,放行
            chain.doFilter(req, rep);
            return;
        }

        //移动端
        //没有匹配上,拦截,判断是否已登录
        Long userId =(Long) req.getSession().getAttribute("user");
        log.info("Settion域中的userId值,为空就没登录,拦截请求:{}",userId);
        if(userId!= null){
            //已登录,在线程域中存储当前用户唯一id标识
            BaseContext.setThreadId(userId);
            log.info("登录已验证(手机端),放行的请求:{}",uri);
            //已登录,放行
            chain.doFilter(req, rep);
            return;
        }

        //未登录,不放行,响应数据
        log.info("已验证,未登录:{}",uri);
        rep.getWriter().write(JSON.toJSONString(R.fail("NOTLOGIN")));



    }
}
